﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Utilities;

namespace HiTeachers.Web
{
    public partial class PostNews : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;

            mtvNews.SetActiveView(vListNews);
        }

        protected void BtnPostNewsClick(object sender, EventArgs e)
        {
            mtvNews.SetActiveView(vAddNews);
            Page.CloseMessage(lblMsg);
        }

        protected void BtnDeleteClick(object sender, EventArgs e)
        {
            if (Request.Form["chkItem"] == null) return;

            string selectedItems = Request.Form["chkItem"];
            string[] selectedItemIds = selectedItems.Split(',');
            foreach (New news in selectedItemIds.Select(t => new Guid(t)).Select(itemId => NewServices.GetNewById(itemId))) NewServices.Delete(news);

            gridData.DataBind();
            udpGrid.DataBind();
        }

        protected void GridDataRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (!"Edit".Equals(e.CommandName)) return;

            if (e.CommandArgument == null) return;

            var itId = new Guid(Convert.ToString(e.CommandArgument));
            New news = NewServices.GetNewById(itId);

            txtTitle.Text = news.Title;
            txtContent.Text = news.Content;
            txtSummary.Text = news.Summary;
            hdfContentId.Value = news.ID.ToString();

            Page.CloseMessage(lblMsg);
            mtvNews.SetActiveView(vAddNews);
        }

        #region Add/Update news View Mothods
        protected void BtnCancelClick(object sender, EventArgs e)
        {
            ClearInputFields();
            gridData.DataBind();
            mtvNews.SetActiveView(vListNews);
        }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

            try
            {
                New news;
                if (string.IsNullOrEmpty(hdfContentId.Value))
                {
                    news = new New
                                   {
                                       Title = txtTitle.Text,
                                       Summary = txtSummary.Text,
                                       Content = txtContent.Text,
                                       UpdatedDate = DateTime.Now
                                   };
                }
                else
                {
                    news = NewServices.GetNewById(new Guid(hdfContentId.Value));

                    news.Title = txtTitle.Text;
                    news.Summary = txtSummary.Text;
                    news.Content = txtContent.Text;
                }

                NewServices.SaveOrUpdate(news);

                ClearInputFields();
                Page.DisplayMessage(lblMsg, "Cập nhật thành công!", MessageType.Success);
                btnCancel.Text = "Đóng";

                SendEmail(news);
            }
            catch (Exception ex)
            {
                Logger.Debug(ex.Message);
                Page.DisplayMessage(lblMsg, "Cập nhật không thành công. Vui lòng cập nhật lại sau", MessageType.Error);
            }
        }
        #endregion

        #region Private Methods

        private void SendEmail(New news)
        {
            IList<LoggerEmail> sbEmails = LoggerEmailServices.GetSubcribeEmails();

            var agrs = new object[] { news, sbEmails };
            System.Threading.ThreadPool.QueueUserWorkItem(SendSubcribeEmails, agrs);
        }

        private void SendSubcribeEmails(object state)
        {
            var args = state as object[];

            if (args == null) return;
            var news = args[0] as New;
            IList<LoggerEmail> sbEmails = args[1] as List<LoggerEmail>;

            // ReSharper disable PossibleNullReferenceException
            string baseMail = "<div style=\"text-align: justify;\">{0}";
            baseMail += "&hellip;&nbsp;<span>(<a href=\"{1}\">Xem thêm&hellip;</a>)</span></div><br /><div>";
            baseMail += "<label style=\"font-weight: bold;\"> LƯU Ý:</label><br /><ul>";
            //baseMail += "<li>Bạn có thể nhấp chuột vào đường dẫn bên dưới để xem chi tiết.<br />";
            //baseMail += "<a href=\"{1}\">{1}</a></li>";
            baseMail += "<li>Bạn có thể hủy việc đăng ký nhận tin tức mới qua email bấc cứ lúc nào bằng cách nhấp chuột vào đường dẫn dưới đây.<br />";
            baseMail += "<a href=\"{2}\">{2}</a></li></ul></div>";

            string newDtlUrl = string.Format("{0}/NewDetails.aspx?itid={1}", SiteUrl, news.ID);
            foreach (LoggerEmail sbEmail in sbEmails)
            {
                var unSubcribeUrl = string.Format("{0}/Subscribe.aspx?subtype=unsub&unsbid={1}", SiteUrl, sbEmail.ID);
                var mailContent = string.Format(baseMail, news.Summary, newDtlUrl, unSubcribeUrl);

                EmailSender.SendMailAsync(string.Format("Hi!Teachers - {0}", news.Title), mailContent, sbEmail.Email);
            }
            // ReSharper restore PossibleNullReferenceException
        }

        private void ClearInputFields()
        {
            txtTitle.Text = string.Empty;
            txtSummary.Text = string.Empty;
            txtContent.Text = string.Empty;
            hdfContentId.Value = string.Empty;
        }
        #endregion
    }
}
